package de.hsb.ai.devil.agent;

import javax.swing.SwingUtilities;

import de.hsb.ai.devil.domain.event.GameOver;
import de.hsb.ai.devil.ui.DevilGui;
import de.hsb.ai.devil.util.Result;

/**
 * InteractivePlayerAgent allows (human) intervention.
 */
@SuppressWarnings("serial")
public class InteractivePlayerAgent extends AbstractDevilPlayer {
	
	private DevilGui gui;
	
	/**
	 * Creates a new interactive agent.
	 */
	public InteractivePlayerAgent() {
		super("human");
	}
	
	@Override
	public int getDelta(int total) {
		Result<Integer> result = new Result<Integer>();
		gui.getDelta(result, total);
		// Wait for the result to come in
		synchronized (result) {
			try {
				result.wait(4000);
			} catch (InterruptedException e) {
				logger.error("get delta", e);
			}
		}
		return result.get(1);
	}
	
	@Override
	public void handle(GameOver g) {
		super.handle(g);
		gui.handleGameOver(g.getWinner().equals(getAID()));
	}
	
	@Override
	protected void setup() {
		super.setup();
		
		initGUI();
	}
	
	@Override
	protected void takeDown() {
		if (gui != null) gui.dispose();
		super.takeDown();
	}
	
	private void initGUI() {		
		SwingUtilities.invokeLater(new Runnable() {
			
			@Override
			public void run() {
				InteractivePlayerAgent.this.gui = new DevilGui(InteractivePlayerAgent.this);
//				InteractivePlayerAgent.this.gui.setVisible(true);
			}
			
		});
	}

}
